package com.eric.controller;

import cn.dev33.satoken.annotation.SaCheckDisable;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.eric.entity.User;
import com.eric.service.GetUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class Login {

    @Autowired
    private GetUserInfoService getUserInfoService;

    @RequestMapping("/doLogin")

    public SaResult doLogin(String userName, String password){
        User loginUser = getUserInfoService.getONeByNameService(userName);
//     登录时，需要校验账号是否已经被封禁，如果被封禁则抛出异常
        StpUtil.checkDisable(loginUser.getId());
        if (loginUser.getLoginname().equals(userName)&&BCrypt.checkpw(password, loginUser.getPassword())){
            StpUtil.login(loginUser.getId(),new SaLoginModel()
                    .setDevice("PC")
                    .setIsLastingCookie(true)
                    .setTimeout(60*60*24*7)
                    .setIsWriteHeader(false)
            );
            loginUser.setPassword(null);
            return SaResult.data(loginUser);
        }
        return SaResult.error();
    }

    @RequestMapping("/doLogout")
    public SaResult doLogout(){
        StpUtil.logout();
        return SaResult.ok("退出登录成功！");
    }
     @RequestMapping("loginInfo")
    public SaResult loginInfo(){
//         获取当前会话账号id，如果没有登录，则抛出异常
        System.out.println(StpUtil.getLoginId());
         System.out.println(StpUtil.getLoginIdAsString());
         System.out.println(StpUtil.getLoginIdAsInt());
         System.out.println(StpUtil.getLoginIdAsLong());
         System.out.println(StpUtil.getLoginIdDefaultNull());
         System.out.println(StpUtil.getTokenValue());
         System.out.println(StpUtil.getTokenName());
         System.out.println(StpUtil.getLoginIdByToken(StpUtil.getTokenValue()));
         System.out.println(StpUtil.isLogin());


         return SaResult.ok();
     }

}
